﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace AutocompleteDemo
{
	public class CitiesHelper
	{
        // Singleton
        private static CitiesHelper m_singleton;

        private List<Location> m_data;

        private CitiesHelper()
        { }

        public string[] GetStates(string prefix, int count)
        {
            var hits = ((from loc in this.Data
                         where loc.State.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
                         select loc.State).Distinct()).Take(count);

            return hits.ToArray();
        }

        public string[] GetCities(string prefix, int count)
        {
            var hits = ((from loc in this.Data
                         where loc.City.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
                         select loc.City).Distinct()).Take(count);

            return hits.ToArray();
        }

        public string[] GetCitiesForState(string prefix, int count, string state)
        {
            var hits = ((from loc in this.Data
                         where loc.State == state && loc.City.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
                         select loc.City).Distinct()).Take(count);

            return hits.ToArray();
        }

        public List<Location> Data
        {
            get { return m_data; }
            set { m_data = value; }
        }

        private void InitializeData()
        {
            string fpath = HttpContext.Current.Server.MapPath("cities.txt");
            m_data = new List<Location>();
            using (StreamReader sr = new StreamReader(fpath))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] cs = line.Split(",".ToCharArray());
                    m_data.Add(new Location(cs[1],cs[0]));
                }
            }
        }

        public static CitiesHelper GetHelper()
        {
            if (null == m_singleton)
                m_singleton = new CitiesHelper();

            m_singleton.InitializeData();

            return m_singleton;
        }
	}
}
